package com.acmen.easyapi.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.util.ResourceUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author acmen
 * @description
 * @since 2021/8/26
 */
public class FilesUtil {
    private static final Logger log = LoggerFactory.getLogger(FilesUtil.class);

    /**
     * 将Byte数组转换成文件
     *
     * @param bytes
     * @param filePath
     * @param fileName
     */
    public static void saveFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && !dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
                log.info("是否创建目录{}，{}", filePath, dir.exists());
            }
            file = new File(filePath + "/" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            log.info("保存文件出错：{}", e);
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void copySourceFile(String sourcePath, String targetPath, List<String> exts) {
        try {
            Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(null).getResources(sourcePath);
            resources:
            for (Resource resource : resources) {
                InputStream inputStream = resource.getInputStream();
                log.info("copyFile path=>{}", resource.getURL().getPath());
                log.info("copyFile fileName=>{}", resource.getFilename());
                String fileName = resource.getFilename();
                String path = resource.getURL().getPath();
                String newTargetPath = targetPath + path.split(fileName)[0].split("static")[1];
                log.info("copyFile newTargetPath=>{}", newTargetPath);
                for (String ext : exts) {
                    if(path.toUpperCase().endsWith(ext.toUpperCase())){
                        saveFileByBytes(inputStreamToByteArray(inputStream), newTargetPath, fileName);
                        continue resources;
                    }
                }
            }
        } catch (Exception e) {
            log.info("copyFile 出错=>{}", e);
        }
    }


    /**
     * 将InputStream转换成byte数组
     *
     * @param input
     * @return
     * @throws IOException
     */
    public static byte[] inputStreamToByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }


    /**
     * 打包文件为zip 并下载
     */
    public static void downloadZip(HttpServletResponse response, String dirPath, String zipName) {
        Path folderPath = Paths.get(dirPath);
        if (!Files.isDirectory(folderPath)) {
            // 文件夹不存在
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            // 二进制数据流
            response.setContentType("application/octet-stream");
            // 附件形式打开
            response.setHeader("Content-Disposition", "attachment; filename=" + new String((zipName + ".zip").getBytes("UTF-8"), "ISO-8859-1"));
            LinkedList<String> path = new LinkedList<>();
            Files.walkFileTree(folderPath, new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    // 开始遍历目录
                    if (!dir.equals(folderPath)) {
                        path.addLast(dir.getFileName().toString());
                        // 写入目录
                        ZipEntry zipEntry = new ZipEntry(path.stream().collect(Collectors.joining("/", "", "/")));
                        try {
                            zipOutputStream.putNextEntry(zipEntry);
                            zipOutputStream.flush();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    // 开始遍历文件
                    try (InputStream inputStream = Files.newInputStream(file)) {
                        // 创建一个压缩项，指定名称
                        String fileName = path.size() > 0
                                ? path.stream().collect(Collectors.joining("/", "", "")) + "/" + file.getFileName().toString()
                                : file.getFileName().toString();
                        ZipEntry zipEntry = new ZipEntry(fileName);
                        // 添加到压缩流
                        zipOutputStream.putNextEntry(zipEntry);
                        // 写入数据
                        int len = 0;
                        // 10kb缓冲区
                        byte[] buffer = new byte[1024 * 10];
                        while ((len = inputStream.read(buffer)) > 0) {
                            zipOutputStream.write(buffer, 0, len);
                        }
                        zipOutputStream.flush();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    return FileVisitResult.CONTINUE;
                }
                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }
                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    // 结束遍历目录
                    if (!path.isEmpty()) {
                        path.removeLast();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            zipOutputStream.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 字体路径，放在资源目录下
    private static final String FONT_PATH = "classpath:static/css/fonts/simsun.ttc";//注意使用字段 模板body字段要加上  style="font-family: SimSun;"

    private static final String LINUX_FONT_PATH = "/usr/share/fonts/dejavu/SIMSUN.TTC";//需要运维安装该字体



    public static HttpServletResponse downloadPdf(HttpServletResponse response,String html,String fileName) {
        try {
            // 清空response
            response.reset();
            // 设置response的Header
            response.setContentType("application/pdf");// 设置输出格式头信息
            response.addHeader("Content-Disposition", "attachment; filename=" +new String(fileName.getBytes("utf-8"),"iso-8859-1"));
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(html.trim());
            // 解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            // 获取字体绝对路径
            String fontPath;
            if (System.getProperty("os.name").toLowerCase().startsWith("win")){
                fontPath = ResourceUtils.getURL(FONT_PATH).getPath();
            }else{
                fontPath = LINUX_FONT_PATH;
            }
            log.info("字体目录：{}",fontPath);
            fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.layout();
            renderer.createPDF(response.getOutputStream());
        } catch (IOException | DocumentException ex) {
            ex.printStackTrace();
        }
        return response;
    }

}
